package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.dto.PageDTO;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryBrandService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: SGS
 * @Date : 2020/11/15 16:38
 * @Version :
 */

@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {


    private final CategoryBrandService categoryBrandService;

    @Autowired
    public BrandServiceImpl(CategoryBrandService categoryBrandService) {
        this.categoryBrandService = categoryBrandService;
    }

    /**
     * 分页查询
     *
     * @param page 当前页
     * @param rows 每页显示数量
     * @param key  关键字
     * @return 分页结果
     */
    @Override
    public PageDTO<BrandDTO> queryBrandByPage(Integer page, Integer rows, String key) {
        // 分页信息的健壮性处理
        page = Math.min(page, 100);
        rows = Math.max(rows, 5);
        // 分页
        Page<Brand> info = new Page<>(page, rows);
        //判断key是否存在
        boolean isKeyExitsts = StringUtils.isNoneBlank(key);
        query().like(isKeyExitsts, "name", key)
                .or()
                .eq(isKeyExitsts, "letter", key)
                .page(info);
        //封装结果
        List<Brand> list = info.getRecords();

        return new PageDTO<>(info.getTotal(), info.getPages(), BrandDTO.convertEntityList(list));
    }

    @Override
    public List<BrandDTO> queryBrandByCategory(Long id) {
        List<CategoryBrand> list = categoryBrandService.query().eq("category_id", id).list();
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        }
        List<Long> brandIds = list.stream().map(CategoryBrand::getBrandId).collect(Collectors.toList());
        List<Brand> brands = listByIds(brandIds);
        return BrandDTO.convertEntityList(brands);
    }

    @Override
    @Transactional
    public void saveBrand(BrandDTO brandDTO) {
        //保存brand品牌信息
        Brand brand = brandDTO.toEntity(Brand.class);
        save(brand);
        //封装中间表对象的集合, 新增一个品牌id对象多个分类id
        List<CategoryBrand> list = brandDTO.getCategoryIds().stream()
                .map(id -> CategoryBrand.of(id, brand.getId()))
                .collect(Collectors.toList());
        //批量写入中间表
        categoryBrandService.saveBatch(list);
    }

    @Override
    @Transactional
    public void updateBrand(BrandDTO brandDTO) {
        //更新brand品牌信息
        Brand brand = brandDTO.toEntity(Brand.class);
        boolean update = updateById(brand);
        if (!update){
            //更新失败
            throw  new LyException(500,"更新品牌失败");
        }
        //根据品牌id删除中间表
        update = categoryBrandService.remove(new QueryWrapper<CategoryBrand>()
                .eq("brand_id",brandDTO.getId()));
        if (!update){
            throw new LyException(500,"更新品牌失败,删除中间表数据出错");
        }
        //重新插入中间表
        List<CategoryBrand> collect = brandDTO.getCategoryIds().stream()
                .map(id -> CategoryBrand.of(id, brandDTO.getId()))
                .collect(Collectors.toList());
        categoryBrandService.saveBatch(collect);
    }

    @Override
    @Transactional
    public void deleteBrand(Long id) {
        //删除品牌表
        removeById(id);
        //删除中间表
        categoryBrandService.remove(
                new QueryWrapper<CategoryBrand>().eq("brand_id",id)
        );
    }
}
